﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using VIA.Foundation;
using VIA.Integration.Domain;
using VIA.Integration.Domain.Production;
using VIA.Presentation;
using VIA.Presentation.Contracts;
using VIA.Presentation.Services;
using VIA.Project.Domain.Services;
using VIA.RbacPassport;
using VIA.SiMoJi.Domain.Inspection;
using VIA.SiMoJi.Domain.Option;

namespace VIA.Project.Presentation.ViewModel.Inspection
{
    [ViewModel(typeof(ISettingsView), IsShared = true)]
    public class SettingsViewModel : ViewModel<ISettingsView>
    {
        #region Field
        readonly IServiceProvider _service;
        private readonly Inspector _inspector;
        readonly IOptionRepository _optionRepository;
        readonly ICommandFactory _commandFactory;
        readonly IMessageService _messageService;
        private readonly IShellService _shellService;
        private readonly IAutoDeleteImage _autoDeleteImage;
        private readonly IFileDialogService _fileDialogService;
        InspectorOption _inspectorOption;
        DataStorageOption _optionStorage;
        private ILogger _logger;
        ICurrentUser _currentUser;
        IDispatcherService _dispatcherService;
        #endregion

        #region Property
        public InspectorOption InspectorOption
        {
            get => _inspectorOption;
            set => SetProperty(ref _inspectorOption, value);
        }
        public DataStorageOption StorageOption
        {
            get => _optionStorage;
            set => SetProperty(ref _optionStorage, value);
        }

        #endregion

        #region Command
        public IRelayCommand SaveOpitonCommand { get; }
        public IRelayCommand ReloadCommand { get; }
        public IRelayCommand SelectedSourceImagePathCommamd { get; }
        public IRelayCommand SelectedResultImagePathCommand { get; }
        public IRelayCommand SelectedCSVDataPathCommand { get; }

        #endregion

        public SettingsViewModel(IServiceProvider service, Inspector inspector, ILogger<SettingsViewModel> logger, IFileDialogService fileDialogService, IShellService shellService, IAutoDeleteImage autoDeleteImage)
        {
            _service = service;
            _inspector = inspector;
            _logger = logger;
            _fileDialogService = fileDialogService;
            _shellService = shellService;
            _autoDeleteImage = autoDeleteImage;
            _dispatcherService = service.GetService<IDispatcherService>();
            _currentUser = service.GetService<ICurrentUser>();
            _optionRepository = service.GetRequiredService<IOptionRepository>();
            _commandFactory = service.GetRequiredService<ICommandFactory>();
            _messageService = service.GetRequiredService<IMessageService>();
            SaveOpitonCommand = _commandFactory.Create(SaveOption, () => _currentUser.IsGranted(PermissionProvider.Settings));
            SelectedSourceImagePathCommamd = _commandFactory.Create(SelectedSourceImagePath);
            SelectedResultImagePathCommand = _commandFactory.Create(SelectedResultImagePath);
            SelectedCSVDataPathCommand = _commandFactory.Create(SelectedCSVDataPath);
            ReloadCommand = _commandFactory.Create(Reload);
            _currentUser = service.GetService<ICurrentUser>();
            _currentUser.UserChanged += (s, e) => _dispatcherService.InvokeAsync(() => SaveOpitonCommand.RaiseCanExecuteChanged());
        }

        private void Reload()
        {
            OnViewLoaded();
        }

        protected override void OnViewLoaded()
        {
            InspectorOption = _optionRepository.Get<InspectorOption>();
            InspectorOption.DataDeleteOption ??= new();
            StorageOption = _optionRepository.Get<DataStorageOption>();
        }

        async void SaveOption()
        {
            try
            {
                _optionRepository.Set(InspectorOption);
                _optionRepository.Set(StorageOption);
                await _optionRepository.SaveAsync();
                _autoDeleteImage.Stop();
                _autoDeleteImage.DataDeleteOption = InspectorOption.DataDeleteOption;
                _autoDeleteImage.DataStorageOption = StorageOption;
                _autoDeleteImage.Run();
                _messageService.ShowMessage("参数保存成功");
            }
            catch (Exception ex)
            {
                _messageService.ShowError(View, "参数保存失败" + ex.Message);
            }
        }
        void SelectedSourceImagePath()
        {
            try
            {
                var str = _fileDialogService.ShowFolderBrowserDialog(_shellService.ShellWindow);
                if (!str.IsNullOrEmpty())
                {
                    StorageOption.SourceImagePath = str;
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                _messageService.ShowError(e);
            }
        }
        void SelectedResultImagePath()
        {
            try
            {
                var str = _fileDialogService.ShowFolderBrowserDialog(_shellService.ShellWindow);
                if (!str.IsNullOrEmpty())
                {
                    StorageOption.ResultImagePath = str;
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                _messageService.ShowError(e);
            }
        }
        void SelectedCSVDataPath()
        {
            try
            {
                var str = _fileDialogService.ShowFolderBrowserDialog(_shellService.ShellWindow);
                if (!str.IsNullOrEmpty())
                {
                    StorageOption.CSVPath = str;
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                _messageService.ShowError(e);
            }
        }
    }
}
